package com.browsesoft.oa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.browsesoft.baseadapter.BlobEntity;
import com.browsesoft.baseadapter.BlobEntityFactory;

/**
 * <p>
 * Title:～～～～
 * </p>
 * <p>
 * Description:
 * 对于"multipart/form-data"形式的form，HttpServletRequest是不进行处理的，它把它作为一个InputStream
 * 往下传。我们拿到这个InputStream，把它解析了出来。对于附件，把它保存到了临时路径
 * PropertiesService.getProperty("attackment",
 * "path");下，具体请看BSMIMEParser类的parse方法。
 * 如果你想把它保存到你的目的地，请用BSHttpServletRequest.saveFile(String fileName,String
 * newPath)方法。
 * <p>
 * Copyright: Copyright (c) 2005
 * </p>
 * <p>
 * Company: BrowseStar
 * </p>
 * 
 * @version 1.0
 */
public class BSHttpServletRequest implements HttpServletRequest, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 
	 */

	private transient HttpServletRequest request = null;

	private transient Map params = null;

	public BSHttpServletRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		String type = request.getContentType();
		if (type != null && type.startsWith("multipart/form-data")) {
			// 调用解析器解析请求request
			BSMIMEParser parser = new BSMIMEParser(request);
			params = parser.getParameters();
			this.setAttribute("parser", parser);
		} else {
			this.params = new HashMap(request.getParameterMap());
		}
	}

	public String getAuthType() {
		return this.request.getAuthType();
	}

	public Cookie[] getCookies() {
		return this.request.getCookies();
	}

	public long getDateHeader(String parm1) {
		return this.getDateHeader(parm1);
	}

	public String getHeader(String parm1) {
		return this.request.getHeader(parm1);
	}

	public Enumeration getHeaders(String parm1) {
		return this.request.getHeaders(parm1);
	}

	public Enumeration getHeaderNames() {
		return this.request.getHeaderNames();
	}

	public int getIntHeader(String parm1) {
		return this.request.getIntHeader(parm1);
	}

	public String getMethod() {
		return this.request.getMethod();
	}

	public String getPathInfo() {
		return this.request.getPathInfo();
	}

	public String getPathTranslated() {
		return this.request.getPathTranslated();
	}

	public String getContextPath() {
		return this.request.getContextPath();
	}

	public String getQueryString() {
		return this.request.getQueryString();
	}

	public String getRemoteUser() {
		return this.request.getRemoteUser();
	}

	public boolean isUserInRole(String parm1) {
		return this.request.isUserInRole(parm1);
	}

	public Principal getUserPrincipal() {
		return this.request.getUserPrincipal();
	}

	public String getRequestedSessionId() {
		return this.request.getRequestedSessionId();
	}

	public String getRequestURI() {
		return this.request.getRequestURI();
	}

	public StringBuffer getRequestURL() {
		return this.request.getRequestURL();
	}

	public String getServletPath() {
		return this.request.getServletPath();
	}

	public HttpSession getSession(boolean parm1) {
		return this.request.getSession(parm1);
	}

	public HttpSession getSession() {
		return this.request.getSession();
	}

	public boolean isRequestedSessionIdValid() {
		return this.request.isRequestedSessionIdValid();
	}

	public boolean isRequestedSessionIdFromCookie() {
		return this.request.isRequestedSessionIdFromCookie();
	}

	public boolean isRequestedSessionIdFromURL() {
		return this.request.isRequestedSessionIdFromURL();
	}

	public boolean isRequestedSessionIdFromUrl() {
		throw new RuntimeException("not support");
	}

	public Object getAttribute(String parm1) {
		return this.request.getAttribute(parm1);
	}

	public Enumeration getAttributeNames() {
		return this.request.getAttributeNames();
	}

	public String getCharacterEncoding() {
		return this.request.getCharacterEncoding();
	}

	public void setCharacterEncoding(String parm1)
			throws java.io.UnsupportedEncodingException {
		this.request.setCharacterEncoding(parm1);
	}

	public int getContentLength() {
		return this.request.getContentLength();
	}

	public String getContentType() {
		return this.request.getContentType();
	}

	public ServletInputStream getInputStream() throws java.io.IOException {
		return this.request.getInputStream();
	}

	public String getParameter(String parm1) {
		String[] obj = (String[]) this.params.get(parm1);
		if (obj == null) {
			return null;
		}
		return obj[0];
	}

	/**
	 * 不区分大小写找参数
	 */
	public String getParameterIgnoreCase(String parm) {
		Iterator iter = this.params.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Entry) iter.next();
			String key = (String) entry.getKey();
			if (key.equalsIgnoreCase(parm)) {
				String[] str = (String[]) entry.getValue();
				return str[0];
			}
		}
		return null;

	}

	public Enumeration getParameterNames() {
		Hashtable ht = new Hashtable(this.params);
		return ht.keys();
	}

	public String[] getParameterValues(String parm1) {
		return this.request.getParameterValues(parm1);
	}

	public Map getParameterMap() {
		return this.params;
	}

	public String getProtocol() {
		return this.request.getProtocol();
	}

	public String getScheme() {
		return this.request.getScheme();
	}

	public String getServerName() {
		return this.request.getServerName();
	}

	public int getServerPort() {
		return this.request.getServerPort();
	}

	public BufferedReader getReader() throws java.io.IOException {
		return this.request.getReader();
	}

	public String getRemoteAddr() {
		return this.request.getRemoteAddr();
	}

	public String getRemoteHost() {
		return this.request.getRemoteHost();
	}

	public void setAttribute(String parm1, Object parm2) {
		this.request.setAttribute(parm1, parm2);
	}

	public void removeAttribute(String parm1) {
		this.request.removeAttribute(parm1);
	}

	public Locale getLocale() {
		return this.request.getLocale();
	}

	public Enumeration getLocales() {
		return this.request.getLocales();
	}

	public boolean isSecure() {
		return this.request.isSecure();
	}

	public RequestDispatcher getRequestDispatcher(String parm1) {
		return this.request.getRequestDispatcher(parm1);
	}

	public String getRealPath(String parm1) {
		throw new RuntimeException("error");
	}

	/**
	 * 把一个给定的文件移到给定的路径下
	 * 
	 * @param fileName 文件名
	 * @param newPath 新的路径 要带最后的/
	 */
	public static boolean saveFile(HttpServletRequest requ, String fileName,
			String newPath) {
		BSMIMEParser parse = (BSMIMEParser) requ.getAttribute("parser");
		String blobId = parse.getBlobID();
		BlobEntity blobEntity = BlobEntityFactory.getInstance().getBlobEntity(
				blobId);
		File cssFile = new File(newPath + fileName);
		FileOutputStream fos = null;
		InputStream is = null;
		int size = 0;
		byte[] buf = new byte[1024];
		try {
			fos = new FileOutputStream(cssFile);
			is = blobEntity.getInputStream();

			while (((size = is.read(buf)) != -1)) {
				fos.write(buf, 0, size);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			try {
				if (fos != null) {
					fos.flush();
					fos.close();
				}
				if (is != null)
					is.close();
			} catch (IOException e) {
			}
		}
		return true;
	}

	public int getRemotePort() {
		// TODO Auto-generated method stub
		return 0;
	}

	public String getLocalName() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getLocalAddr() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getLocalPort() {
		// TODO Auto-generated method stub
		return 0;
	}

	public void setParameter(String name, String value) {
		this.params.put(name, new String[] { value });
	}

	/**
	 * 把String[]转化为String
	 */
	public Map getParameters() {
		Map result = new HashMap();
		Iterator iter = this.params.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry map = (Entry) iter.next();
			String key = (String) map.getKey();
			String[] strings = (String[]) map.getValue();
			result.put(key, strings[0]);
		}
		return result;
	}

}